<template>
	<view class="content">
		<view class="bgColor">
			<image src="/static/examine/msgBg.png" mode=""></image>
		</view>
		<cusHeaderVue titleContent="审批详情" :showBack="true" colorText="#333333"></cusHeaderVue>
		<scroll-view scroll-y="true"
			:style="{paddingTop: `calc(${scrollerHeight} + 90rpx)`,height: `calc(100vh - ${scrollerHeight} - 90rpx`}">
			<view class="contBox" v-if="approvalDetail">
				<view class="contTop">
					<image src="/static/examine/wuliaoshenqing.png" mode=""></image>
					<view class="contTopCont">
						<view class="contName">
							{{ approvalDetail.applicantName }}提交的{{ approvalDetail.processName }}
						</view>
						<template v-if="approvalDetail && approvalDetail.formData">
							<template v-for="(field, index) in approvalDetail.formData" :key="index">
								<view v-if="field && field.label !== '选择物料'" class="contTip">
									<text>{{ field.label }}：</text>
									<template v-if="isImage(field.value)">
										<image :src="field.value" class="preview-image" mode="aspectFit"
											@click="previewImage(field.value)"></image>
									</template>
									<text v-else>{{ field.value }}</text>
								</view>
							</template>
						</template>
					</view>
				</view>
				<view class="personBox">
					<view class="personTop">
						<view class="personTit">
							申请人信息
						</view>
						<view class="personBtn"
							@click="toUrl('/pages/mine/salesRepresentative?id=' + (approvalDetail?.applicantId || ''))">
							个人详情
							<u-icon name="arrow-right" color="#3776F5" size="15"></u-icon>
						</view>
					</view>
					<view class="personName">
						姓名：{{ approvalDetail.applicantName }}
					</view>
					<view class="personTip">
						个人详情可查看打卡、物料领取、请假记录等画像信息
					</view>
				</view>
				<view class="approval">
					<view class="approvalTit">
						审批流
					</view>
					<view class="approvalLi" v-for="(item, index) in approvalDetail.approvalSteps" :key="index">
						<view class="approvalLiCont">
							<view class="approvalPhoto">
								{{ item.approverName ? item.approverName.charAt(0) : '未' }}
								<view class="approvalD" v-if="item.status">
									<image :src="getStatusImage(item.status)" mode=""></image>
								</view>
							</view>
							<view class="approvalCont">
								<view class="approvalName">
									{{ item.approverName || '等待审批' }}
								</view>
								<view class="approvalTime" v-if="item.approveTime">
									{{ item.approveTime }}
								</view>
								<view class="approvalComment" v-if="item.comment">
									审批意见：{{ item.comment }}
								</view>
							</view>
						</view>
						<view class="approvalLine" v-if="index < approvalDetail.approvalSteps.length - 1">
						</view>
					</view>
				</view>
			</view>
			<view class="loading" v-else>
				加载中...
			</view>
		</scroll-view>
		<view class="btnBox" v-if="status ==1&& role">
			<view class="btnLi btnLiA" @click="handleApprove">
				通过
			</view>
			<view class="btnLi" @click="handleReject">
				不通过
			</view>
		</view>
		<!-- 审批意见弹窗 -->
		<u-popup :show="reasonModalVisible" type="bottom">
			<view class="modal-content">
				<view class="modal-header">
					<view class="modal-title">{{ currentAction === 'approve' ? '审批通过' : '审批拒绝' }}</view>
					<view class="modal-close" @click="reasonModalVisible = false">×</view>
				</view>
				<view class="modal-body">
					<view class="reason-label">审批意见</view>
					<textarea v-model="approvalReason" placeholder="请输入审批意见" class="reason-textarea"
						maxlength="200"></textarea>
					<view class="reason-count">{{ approvalReason.length }}/200</view>
				</view>
				<view class="modal-footer">
					<view class="cancel-btn" @click="reasonModalVisible = false">取消</view>
					<view class="confirm-btn" @click="submitApproval">确认</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import {
		ref,
		onMounted,
		computed
	} from 'vue';
	import cusHeaderVue from '@/components/cus-header.vue';
	import {
		GETApprovalDetail,
		PUTTaskApprove,
		PUTTaskReject
	} from '@/api/interface.js';
	import {
		SUBSCRIBE_TYPES,
		promptUserToSubscribe
	} from '@/utils/subscribeMessage.js';

	const scrollerHeight = ref('');
	const approvalDetail = ref(null);
	const status = ref(0);
	const userType = ref('');
	const currentTaskId = ref(''); // 保存当前任务ID
	const approvalReason = ref(''); // 审批意见
	const reasonModalVisible = ref(false); // 是否显示审批意见弹窗
	const currentAction = ref(''); // 当前操作类型：approve 或 reject

	// 判断是否为动销员
	const isSalesPerson = ref(null); // 初始为null，等待获取用户信息后设置
	const role = ref(false); // 审批员角色
	// 获取状态栏高度
	const getBarHeight = () => {

		uni.getSystemInfo({
			success: function(res) {
				scrollerHeight.value = res.statusBarHeight + 'px'
			}
		});
	};

	// 提示用户订阅审批进度通知
	const showApprovalSubscribePrompt = () => {
		promptUserToSubscribe(SUBSCRIBE_TYPES.APPROVAL_PROGRESS);
	};

	// 获取审批详情
	// 保存任务ID
	const fetchApprovalDetail = async (processInstanceId, taskId) => {
		// 保存当前任务ID
		currentTaskId.value = taskId;
		try {
			// 同时传递processInstanceId和taskId参数
			const params = {
				processInstanceId
			};
			if (taskId) {
				params.taskId = taskId;
			}
			const res = await GETApprovalDetail(params);
			console.log('审批详情数据:', res);
			if (res.code === 0 && res.data) {
				// 转换数据格式以适配页面模板
				const apiData = res.data;
				status.value = res.data.status
				const transformedData = {
					// 基本信息	
					applicantName: apiData.processInstance?.startUser?.nickname || '',
					applicantId: apiData.processInstance?.startUser?.id || apiData.processInstance
						?.startUserId || '',
					processName: apiData.processDefinition?.name || '',
					status: mapStatus(apiData.status),
						
					// 转换表单数据
					formData: transformFormData(apiData.processDefinition?.formFields, apiData.processInstance
						?.formVariables),

					// 转换审批步骤
					approvalSteps: transformApprovalSteps(apiData.activityNodes),
				};

				approvalDetail.value = transformedData;
			} else {
				uni.showToast({
					title: res.message || '获取审批详情失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('获取审批详情异常:', error);
			uni.showToast({
				title: '网络错误，请重试',
				icon: 'none'
			});
		}
	}

	// 状态码映射
	const mapStatus = (statusCode) => {
		switch (statusCode) {
			case 1:
				return 'PENDING';
			case 2:
				return 'APPROVED';
			case 3:
				return 'REJECTED';
			default:
				return '';
		}
	};

	// 转换表单数据
	const transformFormData = (formFields, formVariables) => {
		if (!formFields || !formVariables) return [];

		const formData = [];
		// 解析formFields字符串数组
		const parsedFields = formFields.map(fieldStr => {
			try {
				return JSON.parse(fieldStr);
			} catch (e) {
				console.error('解析表单字段失败:', e);
				return null;
			}
		}).filter(Boolean);

		// 构建表单数据
		parsedFields.forEach(field => {
			const value = formVariables[field.field];
			if (value !== undefined) {
				formData.push({
					label: field.title,
					value: Array.isArray(value) ? value.join(', ') : value
				});
			}
		});

		return formData;
	};

	// 转换审批步骤
	const formatTime = (timestamp) => {
	  const date = new Date(timestamp);
	  // 处理时间戳可能为字符串的情况
	  if (isNaN(date.getTime())) {
	    return ''; // 非法时间戳返回空
	  }
	
	  const year = date.getFullYear();
	  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，补零
	  const day = String(date.getDate()).padStart(2, '0');
	  const hour = String(date.getHours()).padStart(2, '0');
	  const minute = String(date.getMinutes()).padStart(2, '0');
	
	  // 统一格式：YYYY-MM-DD HH:MM
	  return `${year}-${month}-${day} ${hour}:${minute}`;
	};
	const transformApprovalSteps = (activityNodes) => {
		if (!activityNodes) return [];

		return activityNodes
			.filter(node => node.nodeType !== 1) // 排除结束节点
			.map(node => {
				const task = node.tasks && node.tasks[0] || {};
				const assignee = task.assigneeUser || {};

				return {
					approverName: assignee.nickname || '',
					status: node.status === 2 ? 'APPROVED' : (node.status === 1 ? 'PENDING' : ''),
					approveTime: node.endTime ? formatTime(node.endTime) : '',
					comment: task.reason || ''
				};
			});
	};

	// 格式化时间
	// const formatTime = (timestamp) => {
	// 	const date = new Date(timestamp);
	// 	return date.toLocaleString('zh-CN', {
	// 		year: 'numeric',
	// 		month: '2-digit',
	// 		day: '2-digit',
	// 		hour: '2-digit',
	// 		minute: '2-digit'
	// 	});
	// };

	// 获取状态对应的图片
	const getStatusImage = (status) => {
		switch (status) {
			case 'APPROVED':
				return '/static/examine/shenpitg.png';
			case 'REJECTED':
				return '/static/examine/wfqd.png';
			default:
				return '';
		}
	}

	// 判断是否为图片路径
	const isImage = (value) => {
		if (!value || typeof value !== 'string') return false;
		// 检查常见图片扩展名
		const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'];
		const lowerValue = value.toLowerCase();
		return imageExtensions.some(ext => lowerValue.includes(ext));
	};

	// 预览图片
	const previewImage = (currentImage) => {
		// 收集所有图片URL用于预览
		const images = approvalDetail.value.formData
			.filter(field => isImage(field.value))
			.map(field => field.value);

		uni.previewImage({
			urls: images,
			current: currentImage,
			loop: true,
			indicator: 'number',
			success: () => {
				console.log('预览图片成功');
			},
			fail: (err) => {
				console.error('预览图片失败:', err);
			}
		});
	};

	// 处理审批通过
	const handleApprove = () => {
		console.log("123");
		currentAction.value = 'approve';
		reasonModalVisible.value = true;
	}

	// 处理审批不通过
	const handleReject = () => {
		console.log("1253");
		currentAction.value = 'reject';
		reasonModalVisible.value = true;
	}

	// 提交审批意见
	const submitApproval = async () => {
		if (!approvalReason.value.trim()) {
			uni.showToast({
				title: '请输入审批意见',
				icon: 'none'
			});
			return;
		}

		if (!currentTaskId.value) {
			uni.showToast({
				title: '任务ID不存在',
				icon: 'none'
			});
			return;
		}

		try {
			const params = {
				id: currentTaskId.value,
				reason: approvalReason.value
			};

			let res;
			if (currentAction.value === 'approve') {
				res = await PUTTaskApprove(params);
			} else {
				res = await PUTTaskReject(params);
			}

			if (res.code === 0) {
				// 显示成功提示
				uni.showToast({
					title: currentAction.value === 'approve' ? '审批通过成功' : '审批拒绝成功',
					icon: 'success',
					duration: 1500
				});

				// 关闭弹窗并清空表单
				reasonModalVisible.value = false;
				approvalReason.value = '';

				console.log('审批成功，准备返回上一页');

				// 延迟返回上一页，让用户看到成功提示
				setTimeout(() => {
					uni.navigateBack({
						delta: 1,
						success: () => {
							console.log('成功返回上一页');
						},
						fail: (err) => {
							console.error('返回上一页失败:', err);
							// 如果返回失败，尝试使用navigateTo跳转到审批列表页面
							uni.navigateTo({
								url: '/pages/examine/examine'
							});
						}
					});
				}, 1500);
			} else {
				uni.showToast({
					title: res.message || (currentAction.value === 'approve' ? '审批通过失败' : '审批拒绝失败'),
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('提交审批失败:', error);
			uni.showToast({
				title: '网络错误，请重试',
				icon: 'none'
			});
		}
	};

	const toUrl = (urlSrc) => {
		uni.navigateTo({
			url: urlSrc
		})
	}
	onLoad((options) => {
		if(options.role && options.role == 1){
			role.value = true;
		}
		console.log('接收到的页面参数:', options);
		getBarHeight();
		// 从页面参数中获取流程实例ID和任务ID
		const processInstanceId = options.processInstanceId || options.id;
		const taskId = options.taskId;

		if (processInstanceId) {
			console.log('获取到的流程实例ID:', processInstanceId);
			console.log('获取到的任务ID:', taskId);
			// 调用详情接口时传递processInstanceId和taskId
			fetchApprovalDetail(processInstanceId, taskId);
		} else {
			console.warn('未获取到流程实例ID');
			uni.showToast({
				title: '参数错误',
				icon: 'none'
			});
		}

		try {
			// 安全地获取用户信息
			const userInfoStr = uni.getStorageSync('userInfo');
			if (userInfoStr) {
				const userInfo = typeof userInfoStr === 'string' ? JSON.parse(userInfoStr) : userInfoStr;
				isSalesPerson.value = userInfo.userType == 0;
				console.log('userInfo:', userInfo);
				console.log('isSalesPerson:', isSalesPerson.value);
			}
		} catch (e) {
			console.error('获取用户信息失败:', e);
			isSalesPerson.value = null;
		}
	});

	onMounted(() => {
		// 获取用户信息
		// const userInfoStr = uni.getStorageSync('userInfo');
		// if (userInfoStr) {
		// 	try {
		// 		const userInfo = JSON.parse(userInfoStr);
		// 		userType.value = userInfo.userType || '';
		// 		// 同时更新isSalesPerson的值
		// 		isSalesPerson.value = userInfo.userType === 0;
		// 		console.log('当前用户类型:', userType.value);
		// 		console.log('isSalesPerson:', isSalesPerson.value);
		// 	} catch (e) {
		// 		console.error('解析用户信息失败:', e);
		// 		isSalesPerson.value = null;
		// 	}
		// }
		// 组件挂载后提示用户订阅审批进度通知
		showApprovalSubscribePrompt();
	});
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		height: 100vh;
	}

	.bgColor {
		width: 100%;
		height: 740rpx;
		position: absolute;
		z-index: -1;
		top: 0;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.contBox {
		padding: 22rpx;
		box-sizing: border-box;
		padding-bottom: calc(env(safe-area-inset-bottom) + 101rpx);

		.contTop {
			width: 100%;
			border-radius: 12.82rpx;
			background: #ffffff;
			box-shadow: 2.56rpx 4.49rpx 10.9rpx 0.64rpx #c0c0c03b;
			padding: 34rpx 32rpx;
			box-sizing: border-box;
			display: flex;

			image {
				width: 89.74rpx;
				height: 89.74rpx;
			}

			.contTopCont {
				margin-left: 28rpx;
				flex: 1;

				.contName {
					font-weight: 500;
					font-size: 33.33rpx;
					color: #1C2027;
					margin-bottom: 25rpx;
				}

				.contTip {
					color: #5a5964;
					font-weight: 400;
					font-size: 25.64rpx;
					line-height: 42.31rpx;
					margin-bottom: 15rpx;
					display: flex;
					align-items: flex-start;
					flex-wrap: wrap;
				}

				.preview-image {
					width: 200rpx;
					height: 200rpx;
					border-radius: 8rpx;
					margin-left: 10rpx;
					margin-top: 10rpx;
					background-color: #f5f5f5;
				}
			}

		}

		.personBox {
			width: 100%;
			border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
			background: #ffffff;
			margin-top: 21rpx;
			padding: 37rpx 33rpx 31rpx;
			box-sizing: border-box;

			.personTop {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.personTit {
					font-weight: 500;
					font-size: 33.33rpx;
					color: #1C2027;
				}

				.personBtn {
					font-size: 25.64rpx;
					font-weight: 400;
					color: #3776F5;
					display: flex;
					align-items: center;
				}

			}

			.personName {
				font-size: 25.64rpx;
				font-weight: 400;
				color: #5A5964;
				margin-top: 28rpx;
			}

			.personTip {
				width: 100%;
				height: 46.79rpx;
				border-radius: 6.41rpx 6.41rpx 6.41rpx 6.41rpx;
				background: #fff7f1;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24.36rpx;
				font-weight: 400;
				color: #FF7834;
				margin-top: 26rpx;
			}
		}

		.approval {
			border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
			background: #ffffff;
			padding: 37rpx 32rpx;
			box-sizing: border-box;
			margin-top: 20rpx;

			.approvalTit {
				font-weight: 500;
				font-size: 33.33rpx;
				color: #1C2027;
				margin-bottom: 27rpx;
			}

			.approvalLi {
				.approvalLiCont {
					display: flex;
					align-items: center;

					.approvalPhoto {
						width: 87rpx;
						height: 87rpx;
						background: #f8c79a;
						border-radius: 50%;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 33.86rpx;
						font-weight: 400;
						color: #FFFFFF;
						position: relative;

						.approvalD {
							width: 26rpx;
							height: 26rpx;
							position: absolute;
							bottom: 5rpx;
							right: 2rpx;

							image {
								width: 100%;
								height: 100%;
							}
						}
					}

					.approvalCont {
						margin-left: 20rpx;
						flex: 1;

						.approvalName {
							font-weight: 500;
							font-size: 30.77rpx;
							color: #1C2027;
						}

						.approvalTime {
							font-size: 25.64rpx;
							font-weight: 400;
							color: #5A5964;
						}

						.approvalComment {
							font-size: 22rpx;
							color: #666666;
							margin-top: 10rpx;
							background-color: #f5f5f5;
							padding: 10rpx 15rpx;
							border-radius: 6rpx;
						}
					}
				}

				.approvalLine {
					height: 139.74rpx;
					margin-left: 43.5rpx;
					border-left: 1px dashed #C9CCD4;
				}
			}
		}

		.loading {
			text-align: center;
			padding: 100rpx 0;
			color: #999999;
			font-size: 28rpx;
		}



	}

	.btnBox {
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: fixed;
		// bottom: calc(env(safe-area-inset-bottom) + 20rpx);
		bottom: 0;
		width: 100%;
		left: 0;
		padding: 20rpx 55rpx calc(env(safe-area-inset-bottom) + 20rpx);
		box-sizing: border-box;
		background: #f2f3f5;

		.btnLi {
			width: 307.37rpx;
			height: 80rpx;
			border-radius: 40.38rpx 40.38rpx 40.38rpx 40.38rpx;
			background: #ffffff;
			box-shadow: 0 3.85rpx 4.49rpx 0 #f9843412;
			font-size: 32.05rpx;
			font-weight: 400;
			color: #F79F31;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.btnLiA {
			background: linear-gradient(-90deg, #feaf38, #f98434);
			box-shadow: 0 3.85rpx 4.49rpx 0 #f984344d;
			color: #ffffff;
		}
	}

	/* 审批意见弹窗样式 */
	.modal-content {
		background: #ffffff;
		border-radius: 20rpx 20rpx 0 0;
		padding-bottom: calc(env(safe-area-inset-bottom) + 30rpx);

		.modal-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 30rpx;
			border-bottom: 1rpx solid #f0f0f0;

			.modal-title {
				font-size: 32rpx;
				font-weight: 500;
				color: #333333;
			}

			.modal-close {
				font-size: 48rpx;
				color: #999999;
				padding: 0 20rpx;
			}
		}

		.modal-body {
			padding: 30rpx;

			.reason-label {
				font-size: 28rpx;
				color: #666666;
				margin-bottom: 20rpx;
			}

			.reason-textarea {
				width: 100%;
				height: 200rpx;
				border: 1rpx solid #e0e0e0;
				border-radius: 10rpx;
				padding: 20rpx;
				box-sizing: border-box;
				font-size: 28rpx;
				color: #333333;
				background-color: #fafafa;
			}

			.reason-count {
				text-align: right;
				font-size: 24rpx;
				color: #999999;
				margin-top: 10rpx;
			}
		}

		.modal-footer {
			display: flex;
			padding: 0 30rpx;

			.cancel-btn {
				flex: 1;
				height: 88rpx;
				background-color: #f5f5f5;
				border-radius: 44rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 32rpx;
				color: #666666;
				margin-right: 20rpx;
			}

			.confirm-btn {
				flex: 1;
				height: 88rpx;
				background: linear-gradient(-90deg, #feaf38, #f98434);
				border-radius: 44rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 32rpx;
				color: #ffffff;
			}
		}
	}
</style>